package services

import (
	"context"
	"easyShop/core/database/elasticsearch"
	"easyShop/model"
	"encoding/json"
	"errors"
	"github.com/olivere/elastic/v7"
	"strconv"
)

func GetProductInfoFromEs(id uint) (model.Product, error) {
	var productInfo model.Product
	conn, _ := elasticsearch.GetConnect()
	// 组建查询器
	search := elastic.NewBoolQuery()
	search.Filter(elastic.NewMatchQuery("id", strconv.Itoa(int(id))))
	// 查询es
	result, err := conn.Search().
		Index("product").
		Query(search).
		From(0).Size(500). //查询起始位和查询个数
		Pretty(true).
		Do(context.Background())

	if err != nil {
		return productInfo, err
	}

	// 获取查询结果总数
	queryCount := result.Hits.TotalHits.Value
	// 读取数据
	if queryCount > 0 {
		for _, hit := range result.Hits.Hits {
			// es查询数据转化为自己定义的结构体
			unmarshalErr := json.Unmarshal(hit.Source, &productInfo)
			if unmarshalErr != nil {
				return productInfo, errors.New("not found")
			}
		}
	} else {
		return productInfo, errors.New("not found")
	}

	return productInfo, nil
}

func SetProductInfoToEs(productInfo model.Product) bool {
	productInfoByte, enJsonErr := json.Marshal(productInfo)
	if enJsonErr != nil {
		return false
	}
	conn, _ := elasticsearch.GetConnect()
	bulk := conn.Bulk()
	request := elastic.NewBulkIndexRequest().
		Index("product").
		Id(strconv.Itoa(int(productInfo.Id))).
		Type("_doc").
		Doc(string(productInfoByte))
	_, err := bulk.Add(request).Do(context.Background())
	if err != nil {
		return false
	}

	return true
}
